package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.core.seekPercentage
import kotlinx.coroutines.CoroutineScope

class ExoPlayerSeekBar : AppCompatSeekBar, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private var fromUser = false

    init {
        setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {//滑动
                    config?.seekBarProgress?.value = Pair(false, progress.toFloat() / max)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                fromUser = true
                config?.singleTapConfirmed?.value = null
                config?.gestureEnable?.value = false
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                fromUser = false
                config?.singleTapConfirmed?.value = true
                config?.gestureEnable?.value = true
                val percentage = progress.toFloat() / max
                //先设置进度
                config?.player?.seekPercentage(percentage)
                //然后再回调
                config?.seekBarProgress?.value = Pair(true, percentage)
            }
        })
    }

    private var config: ExoPlayerViewConfig<IExoPlayerMode>? = null

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        this.config = config
        config.seekBarProgress.observeForever(::onProgressChange)
    }


    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        this.config = null
        config.seekBarProgress.removeObserver(::onProgressChange)
    }

    /**
     * 为了滑动屏幕设置进度后，能立马更新进度
     */
    private fun onProgressChange(pair: Pair<Boolean, Float>?) {
        if (pair?.first == true) {
            updateProgress(config?.player)
        }
    }

    override fun needPlayerListener(): Boolean {
        return true
    }

    override suspend fun onTick(scope: CoroutineScope, player: IPlayer<MediaItem, IExoPlayerMode>) {
        super.onTick(scope, player)
        updateProgress(player)
    }

    private fun updateProgress(player: IPlayer<MediaItem, IExoPlayerMode>?) {
        player ?: return
        if (!fromUser) {
            max = player.duration.toInt()
            secondaryProgress = player.bufferedPosition.toInt()
            progress = player.currentPosition.toInt()
        }
    }

    override suspend fun onModelChange(
        scope: CoroutineScope,
        player: IPlayer<MediaItem, IExoPlayerMode>,
        oldModel: IExoPlayerMode?,
        newModel: IExoPlayerMode
    ) {
        super.onModelChange(scope, player, oldModel, newModel)
        progress = 0
        secondaryProgress = 0
    }
}